package views;

import java.util.Iterator;
import java.util.LinkedList;

import org.eclipse.jface.action.Action;
import org.eclipse.jface.action.GroupMarker;
import org.eclipse.jface.action.IMenuListener;
import org.eclipse.jface.action.IMenuManager;
import org.eclipse.jface.action.IToolBarManager;
import org.eclipse.jface.action.MenuManager;
import org.eclipse.jface.action.Separator;
import org.eclipse.jface.viewers.DoubleClickEvent;
import org.eclipse.jface.viewers.IDoubleClickListener;
import org.eclipse.jface.viewers.IStructuredContentProvider;
import org.eclipse.jface.viewers.ITableColorProvider;
import org.eclipse.jface.viewers.ITableLabelProvider;
import org.eclipse.jface.viewers.LabelProvider;
import org.eclipse.jface.viewers.StructuredSelection;
import org.eclipse.jface.viewers.TableViewer;
import org.eclipse.jface.viewers.TableViewerColumn;
import org.eclipse.jface.viewers.Viewer;
import org.eclipse.swt.SWT;
import org.eclipse.swt.custom.CLabel;
import org.eclipse.swt.events.KeyAdapter;
import org.eclipse.swt.events.KeyEvent;
import org.eclipse.swt.graphics.Color;
import org.eclipse.swt.graphics.Image;
import org.eclipse.swt.layout.FormAttachment;
import org.eclipse.swt.layout.FormData;
import org.eclipse.swt.layout.FormLayout;
import org.eclipse.swt.widgets.Composite;
import org.eclipse.swt.widgets.Display;
import org.eclipse.swt.widgets.Menu;
import org.eclipse.swt.widgets.Table;
import org.eclipse.swt.widgets.TableColumn;
import org.eclipse.swt.widgets.Text;
import org.eclipse.ui.IMemento;
import org.eclipse.ui.ISharedImages;
import org.eclipse.ui.IViewSite;
import org.eclipse.ui.IWorkbenchActionConstants;
import org.eclipse.ui.PartInitException;
import org.eclipse.ui.PlatformUI;
import org.eclipse.ui.part.ViewPart;

import utils.IShowListener;
import utils.SageTvShows;
import utils.Util;
import data.ShowData;

public class ShowsView extends ViewPart implements IShowListener
{
    private static ShowsView instance = null;
    
    public static ShowsView getInstance()
    {
        return instance;
    }

    public ShowsView() 
    {
        instance = this;
        SelectedView.addShowListener(this);
    }
    
    public static final String ID = "ShowsView";
    
    private TableViewer _tableViewer;
    SageTvShows _tvShows = new SageTvShows();
    private Table _table;
    private FormData _formData;
    private Text _searchText;
    private FormData _formData_1;
    private FormData _formData_2;
    private TableColumn showIdCol;
    private TableColumn titleCol;
    private TableColumn fileNameCol;
    private TableColumn dateCol;
    
    private Action deleteItemAction;
    private Action selectAllAction;

    private IMemento memento;

    private Action _transferAction;
    private ShowFilter _filter = null;
    
    private static LinkedList<IShowListener> _listeners = new LinkedList<IShowListener>();

    /**
     * The content provider class is responsible for providing objects to the
     * view. It can wrap existing objects in adapters or simply return objects
     * as-is. These objects may be sensitive to the current input of the view,
     * or ignore it and always show the same content (like Task List, for
     * example).
     */
    class ViewContentProvider implements IStructuredContentProvider {
        public void inputChanged(Viewer v, Object oldInput, Object newInput) {
        }

        public void dispose() {
        }

        public Object[] getElements(Object parent) 
        {
            return _tvShows.getMediaData("").toArray();
        }
    }

    class ViewLabelProvider extends LabelProvider implements
            ITableLabelProvider, ITableColorProvider
    {
        public String getColumnText(Object obj, int index) 
        {
            ShowData showData = (ShowData)obj;
            switch (index)
            {
                case 0:
                    return showData.getShowId();
                case 1:
                    return showData.getTitle();
                case 2:
                    return showData.getDate();
                case 3:
                    return showData.getFileName();
            }
            
            return "";
        }

        public Image getColumnImage(Object obj, int index) {
            return getImage(obj);
        }

        public Image getImage(Object obj) {
            return PlatformUI.getWorkbench().getSharedImages().getImage(
                    ISharedImages.IMG_OBJ_ELEMENT);
        }

        @Override
        public Color getBackground(Object element, int columnIndex)
        {
            ShowData showData = (ShowData)element;
            if (showData.isInSelectedView())
                return Display.getCurrent().getSystemColor(SWT.COLOR_GREEN);
            
            return Display.getCurrent().getSystemColor(SWT.COLOR_LIST_BACKGROUND);
        }

        @Override
        public Color getForeground(Object element, int columnIndex)
        {
            // TODO Auto-generated method stub
            return null;
        }
    }
    
    public void init(IViewSite site, IMemento memento) throws PartInitException
    {
        init(site);
        this.memento = memento;
    }
    

    /**
     * This is a callback that will allow us to create the viewer and initialize
     * it.
     */
    public void createPartControl(Composite parent) 
    {
        Composite cmp = new Composite(parent, SWT.NONE);
        cmp.setLayout(new FormLayout());
        
        _tableViewer = new TableViewer(cmp, SWT.MULTI | SWT.FULL_SELECTION);
        _filter = new ShowFilter();
        _tableViewer.addFilter(_filter);
        
        _tableViewer.addDoubleClickListener(new IDoubleClickListener() {
            public void doubleClick(DoubleClickEvent event) 
            {
               transferItems();
            }
        });
        _table = _tableViewer.getTable();
        _table.setHeaderVisible(true);
        _table.setLinesVisible(true);
        {
            _formData_2 = new FormData();
            _formData_2.bottom = new FormAttachment(100);
            _formData_2.left = new FormAttachment(0);
            _formData_2.height = 184;
            _formData_2.width = 162;
            _table.setLayoutData(_formData_2);
        }
            CLabel label = new CLabel(cmp, SWT.NONE);
            _formData_2.top = new FormAttachment(label, 6);
            
            TableViewerColumn tableViewerColumn = new TableViewerColumn(_tableViewer, SWT.NONE);
            showIdCol = tableViewerColumn.getColumn();
            showIdCol.setWidth(96);
            showIdCol.setText("ShowID");
            
            TableViewerColumn tableViewerColumn_1 = new TableViewerColumn(_tableViewer, SWT.NONE);
            titleCol = tableViewerColumn_1.getColumn();
            titleCol.setWidth(164);
            titleCol.setText("Title");
            
            TableViewerColumn tableViewerColumn_3 = new TableViewerColumn(_tableViewer, SWT.NONE);
            dateCol = tableViewerColumn_3.getColumn();
            dateCol.setWidth(93);
            dateCol.setText("Date");
            
            TableViewerColumn tableViewerColumn_2 = new TableViewerColumn(_tableViewer, SWT.NONE);
            
            fileNameCol = tableViewerColumn_2.getColumn();
            fileNameCol.setWidth(253);
            fileNameCol.setText("File name");
            {
                FormData formData = new FormData();
                formData.left = new FormAttachment(0);
                formData.width = -1;
                formData.top = new FormAttachment(0);
                label.setLayoutData(formData);
            }
        label.setText("Enter program to search:");
        {
            _searchText = new Text(cmp, SWT.BORDER);
            _formData_2.right = new FormAttachment(_searchText, 0, SWT.RIGHT);
            
            _searchText.addKeyListener(new KeyAdapter()
            {
                public void keyReleased(KeyEvent ke) {
                    _filter.setSearchText(_searchText.getText());
                    _tableViewer.refresh();
                }
            });
            {
                _formData_1 = new FormData();
                _formData_1.left = new FormAttachment(label);
                _formData_1.right = new FormAttachment(100);
                _formData_1.top = new FormAttachment(0);
                _searchText.setLayoutData(_formData_1);
            }
        }
        _tableViewer.setContentProvider(new ViewContentProvider());
        _tableViewer.setLabelProvider(new ViewLabelProvider());
        _tableViewer.setInput(getViewSite());
        createActions();
        createToolbar();
        createContextMenu();
//        restoreState();
    }

//    private void restoreState()
//    {
//        LinkedList<ShowData> shows = SelectedView.getInstance().getShows();
//        for (ShowData showData : shows)
//        {
//            showData.setInSelectedView(true);
//        }
//    }

    /**
     * Passing the focus request to the viewer's control.
     */
    public void setFocus() {
        _tableViewer.getControl().setFocus();
    }    
    
    public static void addShowListener(IShowListener listener)
    {
        if (_listeners.contains(listener))
            return;
        
        _listeners.add(listener);
    }
    
    private void sendShowTransfferedEvent(ShowData show)
    {
        for (IShowListener listener : _listeners)
        {
            listener.showTransffered(show);
        }
    }
    
    /**
     * Create toolbar.
     */
    private void createToolbar()
    {
        IToolBarManager mgr = getViewSite().getActionBars().getToolBarManager();
        // mgr.add(addItemAction);
        mgr.add(deleteItemAction);
        mgr.add(_transferAction);
    }
    
    private void createActions()
    {
        deleteItemAction = new Action("Delete")
        {
            public void run()
            {
                deleteItems();
            }
        };
        // deleteItemAction.setImageDescriptor(getImageDescriptor("delete.gif"));
        deleteItemAction
                .setImageDescriptor(Util.getImageDescriptor("delete.gif"));
        selectAllAction = new Action("Select All")
        {
            public void run()
            {
                selectAll();
            }
        };
        
        _transferAction= new Action("Transfer")
        {
            public void run()
            {
                transferItems();
            }
        };
        _transferAction.setImageDescriptor(Util.getImageDescriptor("alt_window_16.gif"));
        
    }
    
    private void createContextMenu()
    {
        // Create menu manager.
        MenuManager menuMgr = new MenuManager();
        menuMgr.setRemoveAllWhenShown(true);
        menuMgr.addMenuListener(new IMenuListener()
        {
            public void menuAboutToShow(IMenuManager mgr)
            {
                fillContextMenu(mgr);
            }
        });

        // Create menu.
        Menu menu = menuMgr.createContextMenu(_tableViewer.getControl());
        _tableViewer.getControl().setMenu(menu);

        // Register menu for extension.
        getSite().registerContextMenu(menuMgr, _tableViewer);
    }
    
    private void fillContextMenu(IMenuManager mgr)
    {
        // mgr.add(addItemAction);
        mgr.add(new GroupMarker(IWorkbenchActionConstants.MB_ADDITIONS));
        mgr.add(deleteItemAction);
        mgr.add(new Separator());
        mgr.add(selectAllAction);
        mgr.add(_transferAction);
    }
    
    protected void deleteItems()
    {
//        ISelection sel = _table.getSelection();
//        for (Iterator iterator = ((StructuredSelection)sel).iterator(); iterator.hasNext();)
//        {
//            Object obj = (Object) iterator.next();
//            _tableViewer.remove(obj);
//            showRemoved((ShowData) obj);
//        }
//        saveState(memento);
    }
    
    private void transferItems()
    {
        for (Iterator iterator = ((StructuredSelection) _tableViewer
                .getSelection()).iterator(); iterator.hasNext();)
        {
            ShowData sel = (ShowData) iterator.next();
            sendShowTransfferedEvent(sel);
            showAdded(sel);
            
        }
        saveState(memento);
    }

    private void selectAll()
    {
        _tableViewer.getTable().selectAll();
    }


    @Override
    public void showAdded(ShowData show)
    {
//        _tvShows.getShowByID(show.getShowId()).setInSelectedView(true);
        if (_tableViewer == null || _table.isDisposed())
            return;
        
        _tableViewer.refresh();
    }


    @Override
    public void showRemoved(ShowData show)
    {
//        _tvShows.getShowByID(show.getShowId()).setInSelectedView(false);
        if (_tableViewer == null || _table.isDisposed())
            return;
        _tableViewer.refresh();
    }
    
    @Override
    public void showTransffered(ShowData show)
    {
        //not in use here
    }

    public void refreshShow(ShowData data, ShowData newShowData)
    {
        _tvShows.remove(data);
        _tableViewer.remove(data);
        _tableViewer.setInput(_tvShows);
    }
    
    
}
